import pandas as pd
import requests,re,json
import datetime
from app.settings import engine

class DataSource(object):
    def __init__(self):
        today = datetime.date.today()
        # print(today)
        # all_dates = pd.read_sql('province',engine)['update_time'].unique()
        query = engine.execute('select distinct update_time from province')
        all_dates = query.cursor.fetchall()
        dates = [d[0] for d in all_dates]
        if today in dates:
            self.df = pd.read_sql(f'select * from province where update_time="{today}"',engine)
            # print('今天有数据')
        else:
            print('今天没有数据,正在联网读取数据')
            response = requests.get('https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5&callback=jQuery35106098672689135465_1621296663070&_=1621296663071')
            res_json = response.text
            result = re.findall('1621296663070\((.*?)\)',res_json)[0]
            result = json.loads(result)
            result = json.loads(result['data'])
            update_time = result['lastUpdateTime']
            area_tree = result['areaTree'][0]['children']
            province_list = []
            for child in area_tree:
                province = {'name': child['name'], 'nowConfirm': child['total']['nowConfirm'],
                            'confirm': child['total']['confirm'],'update_time':update_time}
                province_list.append(province)
            self.df = pd.DataFrame(province_list)
            # 没有主键index也不唯一
            self.df.to_sql('province',engine,if_exists='append',index=False)
    def get_values(self):
        self.province_data = [[], []]
        for name, value, value1 in zip(self.df['name'], self.df['confirm'], self.df['nowConfirm']):
            self.province_data[1].append({'name': name, 'value': value})
            self.province_data[0].append({'name': name, 'value': value1})
        return self.province_data
if __name__ == '__main__':
    DataSource()